<template>
  <div class="app-container">
    <h1>猜你喜欢</h1>
    <div v-if="loading">加载中...</div>
    <div v-else>
      <p><strong>用户ID：</strong>{{ userStore.id }}</p>
      <p><strong>用户名：</strong>{{ userStore.name }}</p>
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['UserTopSongs:UserTopSongs:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格展示 -->
    <el-table v-loading="loading" :data="displayedSongs" style="width: 100%">
      <el-table-column label="序号" width="100" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="歌曲名称" prop="trackTitle" />
      <el-table-column label="歌手" prop="artistName" />
      <el-table-column label="播放次数" prop="trackPlayCount" />
    </el-table>

    <div class="refresh-text" @click="refreshSongs">不感兴趣？换一批</div>

    <!-- 添加或修改用户Top10歌曲对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="UserTopSongsRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="歌曲ID" prop="trackId">
          <el-input v-model="form.trackId" placeholder="请输入歌曲ID" />
        </el-form-item>
        <el-form-item label="播放占比" prop="totalPlayratio">
          <el-input v-model="form.totalPlayratio" placeholder="请输入播放占比" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
      <div>
          <TagRecommend />
      </div>
  </div>

</template>

<script setup name="UserTopSongs">
import {
  listUserTopSongs,
  getUserTopSongs,
  delUserTopSongs,
  addUserTopSongs,
  updateUserTopSongs
} from "@/api/UserTopSongs/UserTopSongs";
import useUserStore from '@/store/modules/user';
import { getRecommendTitles } from "@/api/tracks/tracks.js";
import { computed, onMounted, ref, reactive, toRefs } from "vue";
import TagRecommend from "@/components/personal_charts/TagRecommend.vue";


const userStore = useUserStore();
const open = ref(false);
const loading = ref(true);
const title = ref("");
const recommendList = ref([]);
const displayedSongs = ref([]);  // 存储当前显示的 5 条歌曲
const currentPage = ref(1);
const pageSize = ref(10);

const currentPageData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return recommendList.value.slice(start, end);
});

const data = reactive({
  form: {},
  rules: {
    userId: [
      { required: true, message: "用户ID不能为空", trigger: "blur" }
    ],
  }
});

const { form, rules } = toRefs(data);

onMounted(() => {
  const currentUserId = userStore.id;
  getRecommendList(currentUserId);
});

function getRecommendList(currentUserId) {
  loading.value = true;
  getRecommendTitles(currentUserId).then(response => {
    recommendList.value = response.data.map(item => ({
      trackTitle: decodeURIComponent(item.trackTitle.replace(/\+/g, ' ').replace("/_/", "——")),
      artistName: decodeURIComponent(item.artistName.replace(/\+/g, ' ').replace("/_/", "——")),
      trackPlayCount: item.trackPlayCount
    }));
    refreshSongs(); // 初始时随机展示 5 条歌曲
    loading.value = false;
  }).catch(error => {
    console.error("获取收藏歌曲详情失败：", error);
    loading.value = false;
  });
}

/** 刷新歌曲，随机选择 5 条 */
function refreshSongs() {
  if (currentPageData.value.length < 5) {
    displayedSongs.value = [...currentPageData.value]; // 数据不足 5 条，则显示全部
  } else {
    const shuffled = [...currentPageData.value].sort(() => 0.5 - Math.random());
    displayedSongs.value = shuffled.slice(0, 5);
  }
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    userId: null,
    trackId: null,
    totalPlayratio: null
  };
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加用户Top10歌曲";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _userId = row.userId || ids.value;
  getUserTopSongs(_userId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改用户Top10歌曲";
  });
}
</script>

<style scoped>
.app-container {
    padding: 20px;
}
.refresh-text {
  cursor: pointer;
  margin-top: 0px;
  padding: 20px;
  font-size: 16px;
  text-decoration: none;
  color: #0056b3;
}

.refresh-text:hover {
  color: #007bff;
  text-decoration: underline;
}
</style>
